<template>
	<el-dialog :model-value="visible" width="60%" :z-index="9" top="2vh" @close="cancel">
		<template #header>
			<div class="custom-header">{{ detailid ? (props.isedit ? '编辑' : '查看') : '新增' }}</div>
		</template>

		<div class="boardBox">
			<el-tag v-if="detailid && queryParams.processStage" size="large">{{ getProgressStateName(queryParams.processStage) }}</el-tag>

			<el-form ref="queryForm" label-width="150px" class="mt20" :model="queryParams" :rules="rules">
				<el-form-item label="项目名称" prop="researchName">
					<el-input v-model="queryParams.researchName" placeholder="请输入" clearable :disabled="!props.isedit"></el-input>
				</el-form-item>

				<el-row>
					<el-col :span="8">
						<el-form-item prop="contacts" label="联系人">
							<el-input v-model="queryParams.contacts" placeholder="联系人" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="contactsTel" label="联系电话">
							<el-input v-model="queryParams.contactsTel" placeholder="联系电话" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item prop="contactsEmail" label="联系人邮箱">
							<el-input v-model="queryParams.contactsEmail" placeholder="联系人邮箱" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="principal" label="负责人">
							<el-input v-model="queryParams.principal" placeholder="负责人" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="principalTel" label="负责人电话">
							<el-input v-model="queryParams.principalTel" placeholder="负责人电话" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item prop="principalEmail" label="负责人邮箱">
							<el-input v-model="queryParams.principalEmail" placeholder="负责人邮箱" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="responsibleEnt" label="承办单位">
							<el-input v-model="queryParams.responsibleEnt" placeholder="承办单位" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="projectFunding" label="课题总经费(万元)">
							<el-input v-model="queryParams.projectFunding" placeholder="课题总经费" type="number" :disabled="!props.isedit" min="0"></el-input>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item prop="applyFunding" label="申请经费(万元)">
							<el-input v-model="queryParams.applyFunding" placeholder="申请经费" type="number" :disabled="!props.isedit" min="0"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item prop="selfFunding" label="自筹经费(万元)">
							<el-input v-model="queryParams.selfFunding" placeholder="自筹经费(万元)" type="number" min="0" :disabled="!props.isedit"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="项建书word" prop="wordRecordList">
							<div class="flex" style="width: 100%">
								<el-upload
									ref="uploadRef"
									class="avatar-uploader"
									:limit="1"
									accept=".doc,.docx"
									:action="uploadApi"
									:headers="uploadHeaders"
									:data="uploadData"
									style="width: 90%"
									:multiple="false"
									:file-list="uploadShowPdfList"
									:on-exceed="handleExceed"
									:on-success="handleUploadSuccess"
									:on-error="handleUploadError"
									:on-remove="handleUploadRemove"
									:disabled="!props.isedit"
									:on-preview="handleUploadPdfPreview"
								>
									<!-- :before-upload="beforeUpload" -->
									<el-button v-if="props.isedit" type="sucess">上传文件</el-button>
									<el-button v-if="uploadShowPdfList.length > 0" type="primary" small class="ml20" @click.stop="handleDownload(uploadShowPdfList)"
										>下载文件</el-button
									>
								</el-upload>
							</div>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="项建书盖章版pdf" prop="pdfRecordList">
							<div class="flex" style="width: 100%">
								<el-upload
									ref="uploadRef"
									class="avatar-uploader"
									:limit="1"
									accept=".pdf"
									style="width: 90%"
									:action="uploadApi"
									:headers="uploadHeaders"
									:data="uploadData2"
									:multiple="false"
									:disabled="!props.isedit"
									:file-list="uploadPdfList"
									:on-exceed="handleExceed"
									:on-preview="handleUploadPdfPreview"
									:on-success="handleUploadPdfSuccess"
									:on-error="handleUploadPdfError"
									:on-remove="handleUploadPdfRemove"
								>
									<!-- :before-upload="beforeUpload" -->
									<el-button v-if="props.isedit" type="sucess">上传文件</el-button>
									<el-button v-if="uploadPdfList.length > 0" type="primary" small class="ml20" @click.stop="handleDownload(uploadPdfList)"
										>下载文件</el-button
									>
								</el-upload>
							</div>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="主要研究内容：" prop="researchContents">
					<el-input
						v-model="queryParams.researchContents"
						placeholder="主要研究内容"
						clearable
						type="textarea"
						:disabled="!props.isedit"
						maxlength="300"
						:rows="5"
					/>
				</el-form-item>

				<el-form-item label="技术难点：" prop="techDifficulty">
					<el-input
						v-model="queryParams.techDifficulty"
						placeholder="技术难点"
						clearable
						type="textarea"
						:disabled="!props.isedit"
						maxlength="300"
						:rows="5"
					/>
				</el-form-item>

				<el-form-item label="考核指标：" prop="kpi">
					<el-input v-model="queryParams.kpi" placeholder="考核指标" clearable type="textarea" :disabled="!props.isedit" maxlength="300" :rows="5" />
				</el-form-item>

				<el-form-item v-if="queryParams.documentRecordList.length > 0" label="立项批文：">
					<div class="cursor" @click="handleDownload(queryParams.documentRecordList)">
						{{ queryParams.documentRecordList[0].fileRealName + '.' + queryParams.documentRecordList[0].fileExtName }}
					</div>
				</el-form-item>
			</el-form>
			<div v-if="props.isedit" class="dialog-footer">
				<el-button v-if="detailid" type="primary" plain @click="zancunsumbmit">暂存</el-button>
				<el-button v-if="!detailid" type="primary" @click="submit">保存</el-button>
				<el-button type="primary" @click="allsubmit">提交</el-button>
				<el-button @click="cancel">取消</el-button>
			</div>
		</div>
	</el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'

import { addApi, detailApi, startWorkFlowApi, updateApi } from '@/api/Prospect-project/project-declare'
import { filePreviewByName } from '@/api/sys/upload'
import { UploadFile } from '@/interface/declare'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
const dictionaryStore = useDictionaryStore()
const userStore = useUserStore()
const props = defineProps({
	visible: {
		type: Boolean,
		default: false
	},
	isedit: {
		type: Boolean,
		default: false
	},
	sid: {
		type: String,
		default: ''
	}
})
const editorValue = ref('<p>maku</p>')
const deptoptions = ref([])
const job_modeoptions = ref([])
const filelist = reactive([])

const queryParams = ref({
	id: '',
	researchName: '',
	principal: '',
	principalTel: '',
	principalEmail: '',
	contacts: '',
	contactsTel: '',
	contactsEmail: '',
	responsibleEnt: '',
	projectFunding: null,
	applyFunding: null,
	selfFunding: null,
	researchContents: '',
	techDifficulty: '',
	kpi: '',
	projectManagerA: '',
	projectManagerB: '',
	projectNumber: '',
	applyYear: '',
	processStage: '',
	processStatus: '',
	filingAbstract: '',
	filingKeywords: '',
	isPaper: 1,
	paperRemark: '',
	isBook: 1,
	bookRemark: '',
	isPatent: 1,
	patentRemark: '',
	isTrademark: 1,
	trademarkRemark: '',
	filingName: '',
	filingNumber: '',
	mainCompletionUnits1: '',
	mainCompletionUnits2: '',
	mainCompletionUnits3: '',
	mainCompletionPersion1: '',
	mainCompletionPersion2: '',
	mainCompletionPersion3: '',
	mainCompletionPersion4: '',
	mainCompletionPersion5: '',
	remark: '',
	actualOpeningDate: '',
	actualMidtermDate: '',
	actualCompletionDate: '',
	publishStatus: null,
	publishDate: null,
	approvalReview: null,
	wordRecordList: [],
	pdfRecordList: [],
	documentRecordList: []
})

const getProgressStateName = (row: any) => {
	switch (row) {
		case '0':
			return '申报中'
		case '1':
			return '预审'
		case '2':
			return '立项评审(最终结论) '
		case '3':
			return '开题'
		case '4':
			return '中期'
		case '5':
			return '结题'
		case '6':
			return '等待归档'
		case '7':
			return '归档'
	}
}
const emit = defineEmits<{ (event: 'update:visible', value: boolean): void; (event: 'success', value: ''): void }>()
// 获取表单引用
const queryForm = ref(null)
const uploadRef = ref(null)
const unitCount = ref(0)
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'ResearchProjectProposalWord',
	remark: '项目建议书word'
}
const uploadData2 = {
	extCode: 'ResearchProjectProposalStampedVersionPdf',
	remark: '项目建议书盖章版pdf'
}

const uploadPdfRef = ref<UploadInstance>()
const uploadPdfList = ref<UploadFile[]>([])

const uploadShowPdfList = ref<UploadRawFile[]>([])
const uploadShowList = ref<UploadRawFile[]>([])
const detailid = ref('')
// 监听 localValue 的变化，通知父组件更新值
watch(
	() => props.visible,
	newValue => {
		if (newValue) {
			detailid.value = ''
			const data = {
				id: '',
				researchName: '',
				principal: '',
				principalTel: '',
				principalEmail: '',
				contacts: '',
				contactsTel: '',
				contactsEmail: '',
				responsibleEnt: '',
				projectFunding: null,
				applyFunding: null,
				selfFunding: null,
				researchContents: '',
				techDifficulty: '',
				kpi: '',
				projectManagerA: '',
				projectManagerB: '',
				projectNumber: '',
				applyYear: '',
				processStage: '',
				processStatus: '',
				filingAbstract: '',
				filingKeywords: '',
				isPaper: 1,
				paperRemark: '',
				isBook: 1,
				bookRemark: '',
				isPatent: 1,
				patentRemark: '',
				isTrademark: 1,
				trademarkRemark: '',
				filingName: '',
				filingNumber: '',
				mainCompletionUnits1: '',
				mainCompletionUnits2: '',
				mainCompletionUnits3: '',
				mainCompletionPersion1: '',
				mainCompletionPersion2: '',
				mainCompletionPersion3: '',
				mainCompletionPersion4: '',
				mainCompletionPersion5: '',
				remark: '',
				actualOpeningDate: '',
				actualMidtermDate: '',
				actualCompletionDate: '',
				publishStatus: null,
				publishDate: null,
				approvalReview: null,
				wordRecordList: [],
				pdfRecordList: [],
				documentRecordList: []
			}
			queryParams.value = data

			uploadPdfList.value = []
			uploadShowPdfList.value = []
			uploadShowList.value = []
			uploadPdfRef.value?.clearFiles()
			uploadRef.value?.clearFiles()

			if (props.sid) {
				detailid.value = props.sid
				getDetail(props.sid)
			}
		}
	}
)

const info = ref({ url: '', qrcode: '' })
const addvisible = ref(false)

const rules = reactive({
	researchName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
	principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
	principalTel: [
		{ required: true, message: '请输入负责人手机号', trigger: 'blur' },
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入有效的手机号',
			trigger: 'blur'
		}
	],
	principalEmail: [
		{ required: true, message: '请输入负责人邮箱', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
			message: '请输入有效的邮箱地址',
			trigger: 'blur'
		}
	],
	contacts: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
	contactsTel: [
		{ required: true, message: '请输入联系人手机号', trigger: 'blur' },
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入有效的手机号',
			trigger: 'blur'
		}
	],
	contactsEmail: [
		{ required: true, message: '请输入联系人邮箱', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
			message: '请输入有效的邮箱地址',
			trigger: 'blur'
		}
	],
	responsibleEnt: [{ required: true, message: '请输入承担单位', trigger: 'blur' }],
	projectFunding: [{ required: true, message: '请输入课题总经费', trigger: 'blur' }],
	applyFunding: [{ required: true, message: '请输入申请经费', trigger: 'blur' }],

	selfFunding: [{ required: true, message: '请输入自筹经费', trigger: 'blur' }],
	researchContents: [{ required: true, message: '请输入研究内容', trigger: 'blur' }],
	techDifficulty: [{ required: true, message: '请输入技术难点', trigger: 'blur' }],
	kpi: [{ required: true, message: '请输入考核指标', trigger: 'blur' }],
	wordRecordList: [{ required: true, message: '请上传文件', trigger: 'change' }],
	pdfRecordList: [{ required: true, message: '请上传文件', trigger: 'change' }]
})
const jobstatusoptions = ref([
	{ value: 1, name: '试用' },
	{ value: 2, name: '正式' }
])
const props1 = reactive({
	checkStrictly: true,
	emitPath: false,
	multiple: false,
	value: 'id',
	label: 'name',
	children: 'children'
})

// 下载文件逻辑
const handleDownload = async (file: any) => {
	// 替换为你的下载逻辑
	console.log('下载功能待实现', file)
	const url = window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + `/api/files/${file[0].id}/downloadByFileId`
	await downloadFile(url, file[0])
}

async function downloadFile(url, row: any) {
	try {
		// 发起请求
		const response = await fetch(url, {
			method: 'GET',
			headers: {
				Authorization: userStore.token, // 在 Header 中传递 token
				'Content-Type': 'application/json' // 根据实际需求设置 Content-Type
			}
		})

		if (!response.ok) {
			throw new Error(`下载失败: ${response.statusText}`)
		}

		// 获取文件数据
		const blob = await response.blob()

		// 创建下载链接
		const downloadLink = document.createElement('a')
		downloadLink.href = URL.createObjectURL(blob)
		downloadLink.download = row.fileRealName ? row.fileRealName : row.name // 设置下载文件名(根据实际需求修改)
		document.body.appendChild(downloadLink)
		downloadLink.click()
		document.body.removeChild(downloadLink)
	} catch (error) {
		console.error('下载过程中出错:', error)
	}
}
// const selectedArrRef = ref(null)
// function handleChange(value) {
// 	selectedArrRef.value.togglePopperVisible()
// }
const getDetail = (id: String) => {
	detailApi({ id: id }).then(res => {
		queryParams.value = res.data
		uploadPdfList.value = res.data.pdfRecordList.map((item: any) => {
			return {
				...item,
				name: item.fileRealName
			}
		})

		uploadShowPdfList.value = res.data.wordRecordList.map((item: any) => {
			return {
				...item,
				name: item.fileRealName
			}
		})
	})
}

const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const handleUploadPdfSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadPdfList.value.push(res.data)

		queryParams.value.pdfRecordList = uploadPdfList.value
	} else {
		handleUploadPdfError(res, uploadFile)
	}
}

const beforeUploadPdf = (file: UploadRawFile) => {
	const allowedTypes = ['application/pdf']
	const fileExtension = file.name.split('.').pop()?.toLowerCase()
	if (!allowedTypes.includes(file.type) || fileExtension !== 'pdf') {
		ElMessage.error('仅支持上传 PDF 文件')
		return false
	}
	return true
}

const handleUploadPdfRemove = (file: UploadRawFile) => {
	uploadPdfList.value = []
	queryParams.value.pdfRecordList = []
}

const handleUploadPdfError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadPdfList.value = uploadPdfList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
	queryParams.value.pdfRecordList = uploadPdfList.value
}

const handleUploadSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadShowPdfList.value.push(res.data)
		queryParams.value.wordRecordList = uploadShowPdfList.value
	} else {
		handleUploadError(res, uploadFile)
	}
}

const handleUploadRemove = (file: any) => {
	uploadShowPdfList.value = []
	queryParams.value.wordRecordList = []
}
const handleUploadError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowList.value = uploadShowList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}

const submit = () => {
	queryForm.value.validate((valid: boolean) => {
		if (valid) {
			const arr1 = changearr1()
			const arr2 = changearr2()
			const data = {
				...queryParams.value,
				wordRecordList: arr1,
				pdfRecordList: arr2,
				id: detailid.value ? detailid.value : ''
			}

			if (!detailid.value) {
				console.log('data', data)
				delete data.id
			}
			addApi(data).then(res => {
				detailid.value = res.message
				ElMessage.success('保存成功')
				emit('update:visible', false)
				queryForm.value?.resetFields()

				emit('success', '')
			})
		}
	})
}

const changearr1 = () => {
	if (uploadShowPdfList.value.length > 0) {
		const arr = uploadShowPdfList.value.map(item => {
			const obj = {
				id: item.id,
				fileRealName: item.fileRealName,
				fileExtName: item.fileExtName,
				systemFileName: item.systemFileName,
				filePath: item.filePath,
				fileSize: item.fileSize,
				extCode: item.extCode
			}
			return obj
		})
		return arr
	}
}
const changearr2 = () => {
	if (uploadPdfList.value.length > 0) {
		const arr = uploadPdfList.value.map(item => {
			const obj = {
				id: item.id,
				fileRealName: item.fileRealName,
				fileExtName: item.fileExtName,
				systemFileName: item.systemFileName,
				filePath: item.filePath,
				fileSize: item.fileSize,
				extCode: item.extCode
			}
			return obj
		})
		return arr
	}
}
const zancunsumbmit = () => {
	const arr1 = changearr1()
	const arr2 = changearr2()

	const data = {
		...queryParams.value,
		wordRecordList: arr1,
		pdfRecordList: arr2,
		id: detailid.value ? detailid.value : ''
	}
	updateApi(data).then(res => {
		ElMessage.success('暂存成功')
		emit('update:visible', false)
		emit('success', '')

		queryForm.value?.resetFields()
	})
}

const allsubmit = () => {
	console.log(queryParams.value.wordRecordList, 'queryParams.value.wordRecordList')
	queryForm.value.validate((valid: boolean) => {
		if (valid) {
			const arr1 = changearr1()
			const arr2 = changearr2()
			const data = {
				...queryParams.value,
				wordRecordList: arr1,
				pdfRecordList: arr2,
				id: detailid.value ? detailid.value : ''
			}

			startWorkFlowApi(data).then(res => {
				ElMessage.success('提交成功')
				queryForm.value?.resetFields()
				emit('update:visible', false)
				emit('success', '')
			})
		}
	})
}

function cancel() {
	emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
.boardBox {
	display: flex;
	align-items: center;
	flex-direction: column;
	flex-wrap: wrap;
	justify-content: space-around;
	overflow-y: scroll;
	height: 100%;

	&::-webkit-scrollbar {
		display: none;
	}

	-ms-overflow-style: none;
	scrollbar-width: none;

	.tishi {
		font-size: 14px;
		color: #999;
		background-color: #f3f8fb;
		padding: 5px 10px;
		border-radius: 6px;
	}
}
</style>
